package com.hzd.rate;

import ablaze.framework.utils.JSONUtils;
import ablaze.framework.utils.MapUtils;
import ablaze.framework.utils.StringUtils;
import ablaze.framework.utils.ValidateUtils;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 流量包工具类
 *
 * @author christ
 * @date 2015/11/4
 */
public class RateSDK {

    private static Logger logger = LoggerFactory.getLogger(RateSDK.class);


    /**
     * 获得token
     *
     * @return
     */
    public static String getToken() throws RateException {

        // appkey
        String appkey = RateSDKConfig.APP_KEY;

        // appsecret先进行md5加密
        String appsecret = DigestUtils.md5Hex(RateSDKConfig.APP_SECRET);

        // 准备签名运算
        Map param = MapUtils.toMap("appkey", appkey, "appsecret", appsecret);

        // 计算并添加签名参数
        param.put("sign", sign(param));

        HttpRequest request = HttpRequest.post(RateSDKConfig.SERVER_URL + "getToken").contentType("application/json");

        // 发送json参数
        request.body(JSONUtils.serialize(param));

        // 获得结果
        HttpResponse response = request.send();

        if (response != null && response.statusCode() != 200) {
            throw new RateException("流量发送平台调用getToken>>请求返回的http状态码为：" + response.statusCode());
        }

        // 解析返回的结果
        String json = response.bodyText();
        if (ValidateUtils.isNotEmpty(json)) {
            Map result = JSONUtils.deserialize(json, Map.class);
            if ("000".equals(result.get("code"))) {
                Map data = (Map) result.get("data");
                return (String) data.get("token");
            } else {
                throw new RateException("流量发送平台调用getToken>>返回的状态码为：" + result.get("code"));
            }
        }
        return null;
    }

    /**
     * 发流量包给用户
     *
     * @param mobile
     * @param extNO
     * @param rate
     * @return
     */
    public static String placeOrder(String mobile, String extNO, String rate) throws RateException {

        // 日志操作
        logger.info(StringUtils.parseTemplate("流量发送平台调用placeOrder>>mobile=${mobile} , extNO=${extNO} , rate=${rate}",
                MapUtils.toMap("mobile", mobile, "extNO", extNO, "rate", rate)));

        // 参数
        Map param = MapUtils.toMap(
                "appkey", RateSDKConfig.APP_KEY,
                "token", getToken(),
                "mobile", mobile,
                "postpackage", rate,
                "extno", extNO,
                "fixtime", null,
                "appver", "Http",
                "apiver", "2.0",
                "des", "0"
        );

        // 计算并添加签名参数
        param.put("sign", sign(param));

        HttpRequest request = HttpRequest.post(RateSDKConfig.SERVER_URL + "placeOrder").contentType("application/json");

        // 发送json参数
        request.body(JSONUtils.serialize(param));

        // 获得结果
        HttpResponse response = request.send();

        if (response != null && response.statusCode() != 200) {
            throw new RateException("流量发送平台调用placeOrder>>请求返回的http状态码为：" + response.statusCode());
        }

        String json = response.bodyText();

        if (ValidateUtils.isNotEmpty(json)) {
            Map result = JSONUtils.deserialize(json, Map.class);
            if ("000".equals(result.get("code"))) {
                Map data = (Map) result.get("data");
                return (String) data.get("orderNO");
            } else {
                throw new RateException("流量发送平台调用placeOrder>>返回的状态码为：" + result.get("code"));
            }
        }
        return null;
    }

    /**
     * 签名
     *
     * @param param
     * @return
     */
    public static String sign(Map<String, Object> param) {

        List<String> keys = new ArrayList(param.keySet());

        Collections.sort(keys);

        List<String> params = new ArrayList<>();
        for (String key : keys) {
            if (ValidateUtils.isNotEmpty(param.get(key))) {
                params.add(key + "" + param.get(key));
            }
        }

        String join = StringUtils.join(params, "");

        // 采用sha1对要签名的内容做算法摘要
        return DigestUtils.shaHex(join);
    }

    public static void main(String[] args) {
        RateSDKConfig.SERVER_URL = "http://api.tenchang.com/server/";
        RateSDKConfig.APP_KEY = "ffPraMgzhG";
        RateSDKConfig.APP_SECRET = "7LtyMC0bWBxZHisa";
        System.out.println(RateSDK.placeOrder("17750603305", "01", "YD10;DX5;LT20"));
    }

}
